/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */

// 引入 lodash 库，用于数据处理和操作
const _ = require('lodash')
// 引入 await-to-js 库，用于处理异步操作
const { to } = require('await-to-js')
// 引入 moment 库，用于日期和时间操作
const moment = require('moment')
// 引入 fs 模块，用于文件系统操作
const fs = require('fs')
// 引入 fs.promises 模块，用于文件系统操作
const fsPromises = require('fs').promises
// 引入 path 模块，用于处理文件和目录路径
const path = require('path')
// 引入 esm 库，用于在 Node.js 中支持 ES6 模块
const esm = require('esm')
// 使用 esm 配置来加载模块
const requireModule = esm(module)

// 引入 mysql2 库，用于连接 MySQL 数据库
const mysql = require('mysql2')

// 设置 MySQL 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'root', // rfy mengxiang55 jjy root
  database: 'macau',
  waitForConnections: true,
  connectionLimit: 50, // 最大连接数 mac: 50, jjy: 100
  connectTimeout: 10000 // 连接超时时间，单位毫秒
}

const { region } = requireModule(path.join(__dirname, '../src/utils/modules/settings.js'))

// 业务类型
const businessType = region === 'm' ? 'macau' : 'hongkong'

// 创建 MySQL 连接池
const pool = mysql.createPool(dbConfig).promise()

// 创建 MySQL 单一连接
const connection = mysql.createConnection(dbConfig)

// 获取项目根目录
const ROOT_DIR = path.join(__dirname, '..')
// helpers 目录
const HELPERS_DIR = path.join(ROOT_DIR, 'helpers')

const { initDatabase, safeInitDatabase } = require(path.join(HELPERS_DIR, 'initDatabase.js'))

// 读取并构建 fixedGroupMapObject
const { finalGroupMap, flatGroupMap, groupArray } = requireModule(path.join(HELPERS_DIR, 'readGroup.js'))

// allValues = allValues // .slice(0, 20)

// 历史表
const HISTORY_RESULTS_TABLE = businessType + '_history_results'
// 当前组表
const CURRENT_GROUP_INFOS_TABLE = businessType + '_current_group_infos'
// 杀前组表
const GROUP_ACCURACY_TABLE = businessType + '_group_accuracy'
// 杀前组统计表
const DAILY_GROUP_ACCURACY_SUMMARY_TABLE = businessType + '_daily_group_accuracy_summary'

const GROUP_ACCURACY_MAP_FILE = businessType + '_GroupAccuracyMap.json'

// 获取所有历史记录
// const { getAllHistoryResults } = require(path.join(HELPERS_DIR, 'getAllHistoryResults.js'))
// 插入历史记录
const { insertHistoryResults } = require(path.join(HELPERS_DIR, 'insertHistoryResults.js'))
// 插入当前组信息
const { insertCurrentGroupInfos } = require(path.join(HELPERS_DIR, 'insertCurrentGroupInfos.js'))
// 插入杀前组表数据
const { insertGroupAccuracy } = require(path.join(HELPERS_DIR, 'insertGroupAccuracy.js'))
// 插入杀前组统计表数据
const { insertDailyGroupAccuracySummary } = require(path.join(HELPERS_DIR, 'insertDailyGroupAccuracySummary.js'))
// 更新历史表预测等字段数据
const { updateHistoryForecast } = require(path.join(HELPERS_DIR, 'updateHistoryForecast.js'))

// 初始化分组和杀前组映射对象
const { initGroupAccuracyMap } = require(path.join(HELPERS_DIR, 'initGroupAccuracyMap.js'))

const { calcAccuracySummary } = require(path.join(HELPERS_DIR, 'calcAccuracySummary.js'))

const { filterForecaArray } = require(path.join(HELPERS_DIR, 'filterForecaArray.js'))

const { getLuckAndForecastGroupNames } = require(path.join(HELPERS_DIR, 'getLuckAndForecastGroupNames.js'))

// 读取所有数据
const { readAllValues } = require(path.join(HELPERS_DIR, 'readAllValues.js'))

const allValues = readAllValues('m').slice(0, 10)
// console.log(allValues.length)

const allNumbers = Array.from({ length: 49 }, (_, i) => i + 1).map((num) => (num < 10 ? `0${num}` : `${num}`))

// console.log(allNumbers)
// console.log(flatGroupMap)

// 初始化目标对象，每个数字对应空对象
const numberGroupMap = allNumbers.reduce((acc, num) => {
  acc[num] = {}
  return acc
}, {})

// 遍历每个分组
Object.entries(flatGroupMap).forEach(([groupName, groups]) => {
  // groups是包含两个子数组的数组
  groups.forEach((group, groupIndex) => {
    group.forEach((num) => {
      // 将数字转为两位字符串，如2 -> '02'
      const numStr = num.toString().padStart(2, '0')
      // 确保该数字在映射中存在
      if (numberGroupMap[numStr]) {
        // 将分组名称和子数组索引存入
        numberGroupMap[numStr][groupName] = groupIndex
      }
    })
  })
})

// 输出结果示例
console.log(numberGroupMap['02']['TWO_ODD_EVEN_GROUPS'])

// 同步写入文件 28M
// fs.writeFileSync(path.join(__dirname, 'numberGroupMap.json'), JSON.stringify(numberGroupMap, null, 2), 'utf8')

// 所有组的是否准确数据

// let a = { age: 12, name: 'xxx', gender: 'male' } // 示例对象

const r1 = _.mapValues(flatGroupMap, (value, key) => {
  return {
    accuracyList: []
  }
})

// console.log(r1)
// console.log(allValues.length)
// console.log(Object.keys(flatGroupMap).length)

Object.keys(flatGroupMap).forEach((key) => {
  // console.log(key)

  r1[key].accuracyList = allValues.map((item, index) => {
    if (index === 0) {
      return 1
    } else {
      // index 从 1 开始
      const prevNumber = allValues[index - 1].number
      const prevIndex = numberGroupMap[prevNumber][key]
      const prevGroup = flatGroupMap[key][prevIndex]
      return prevGroup.map(Number).includes(Number(item.number)) ? 0 : 1
    }
  })
})

// console.log(Object.keys(r1).length)
// console.log(r1['SIX_ASCENDING_GROUPS'])

const sortResults = (a, b) => {
  if (b.stats.accuracyRate !== a.stats.accuracyRate) {
    return b.stats.accuracyRate - a.stats.accuracyRate // accuracy_rate 降序
  }
  return a.stats.maxConsecutiveIncorrect - b.stats.maxConsecutiveIncorrect // max_consecutive_incorrect 升序
}

const r2 = allValues.map((item, index) => {
  // todo 挑组
  // todo 挑号
  // todo 是否准确
  // return {
  // ...item,
  // todo groupNames: [],
  // todo luckyArray: [],
  // todo killArray: [],
  // todo accuracy: 0,
  // }

  if (index < 2) {
    return {
      ...item,
      groupNames: [],
      luckyArray: [],
      killArray: [],
      accuracy: 1
    }
  } else {
    // const currentAccuracyList = r1[key].slice(0, index + 1)

    if (index === 2) {
      // console.log(r1['SIX_ASCENDING_GROUPS'])
      const currentAccuracyMap = _.chain(r1)
        .mapValues((value, key) => {
          const currentAccuracyList = value.accuracyList.slice(0, index + 1)
          const stats = calcAccuracySummary(currentAccuracyList)
          // if (key === 'SIX_ASCENDING_GROUPS') {
          //   console.log(stats)
          // }
          return {
            accuracy_array: currentAccuracyList,
            stats
          }
        })
        .value()
      const currentGroupArray = Object.keys(currentAccuracyMap).map((key) => ({
        groupName: key,
        ...currentAccuracyMap[key]
      }))
      // console.log(currentAccuracyMap['SIX_ASCENDING_GROUPS'])
      // console.log(currentGroupArray.length) // 15754
      // console.log(currentGroupArray[0])

      // 过滤预测数组
      const { redContinuousLimit2Group, greenReboundRedNonContinuousGroup, greenContinuousGroup } = filterForecaArray(
        currentGroupArray,
        sortResults
      )

      // console.log(redContinuousLimit2Group.length)
      // console.log(greenReboundRedNonContinuousGroup.length)
      // console.log(greenContinuousGroup.length)

      // console.log(redContinuousLimit2Group[0])

      // 获取幸运和杀前组组名
      const { kill_array, lucky_array, red_continuous_limit_2, green_rebound_red_non_continuous, green_continuous } =
        getLuckAndForecastGroupNames(
          redContinuousLimit2Group,
          greenReboundRedNonContinuousGroup,
          greenContinuousGroup,
          item,
          numberGroupMap,
          flatGroupMap
        )
      // console.log(kill_array)
      // console.log(lucky_array)
      // console.log(red_continuous_limit_2)
      // console.log(green_rebound_red_non_continuous)
      // console.log(green_continuous)
    }
    return {
      ...item,
      groupNames: [],
      luckyArray: [],
      killArray: [],
      accuracy: 0
    }
  }
})

// console.log(r2.slice(0, 3))
